import re
import sys
import os
import subprocess
import json
from rich import print, print_json
from rich.console import Console
console = Console()

thisPath = os.path.split(os.path.realpath(__file__))[0]
jsonDataF = f'{thisPath}/json_data/test.json'
# print(thisPath)

# 位置参数判断
argv = sys.argv
argvLen = len(argv)
if argvLen < 2 or argvLen > 4:
  print(f"argv: {argv} 错误，位置参数应该是：【gd路径，视频后缀，匹配字符串】")
  sys.exit()
gdP = argv[1]
suffix = ''
strP = ''
if argvLen >= 3:
  suffix = argv[2]
  if argvLen == 4:
    strP = argv[3]
# print(gdP, suffix, strP)

lsJCmd = f"rclone lsjson -R --hash {gdP} |sed 's/gclone sa file:.*\.json//'"
runres = subprocess.run(lsJCmd, stdout=subprocess.PIPE, shell=True)
jsonRes = json.loads(runres.stdout)
# print(jsonRes)

videoFs = []
for gdf in jsonRes:
  size = gdf['Size']
  isDir = gdf['IsDir']

  # 目录 排除掉
  if isDir:
    continue

  # 小于100M 的排除掉
  if int(size)/1024**2 < 100:
    continue

  # if gdf['MimeType'].find('video/') == 0: 'MimeType': 'application/octetstream'
  path = gdf['Path']
  name = gdf['Name']

  thisFIsOk = False

  # console.log()
  if suffix:
    if re.findall(rf'\.{suffix}$', name):
      if strP:
        if re.findall(rf'{strP}', path):
          thisFIsOk = True
      else:
        thisFIsOk = True
  else:
    thisFIsOk = True
  if thisFIsOk:
    videoFs.append(path)

if not videoFs:
  console.log("没有匹配的文件")
  sys.exit()

# 排序
# nums = set()
# for videoF in videoFs:
#   fn = re.findall(r'[^/]+$', videoF)[0]
#   fnNum = re.findall(r'\d+', fn)[-1]
#   nums.add(fnNum)
# # 如果每个文件名都有数字，且这些最后一个数字没有重复的，则按这个数值排序
# if len(nums) == len(videoFs):
#   videoFs.sort(key=lambda x: int(re.findall(r'\d+', x)[-1]))

fsJson = {'videoFs': videoFs, "gdP": gdP}
with open(jsonDataF, 'w', encoding='utf8') as f:
  json.dump(fsJson, f, indent=2, ensure_ascii=False)

# print_json(json.dumps(fsJson, ensure_ascii=False))
print(fsJson, len(videoFs))
